﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Assist;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using YArchitech.LIB.YJKControls;
using YJKArchMethodLibrary.Utils;

namespace WallCreateAndEdit.WallModule
{
	public partial class DlgCurvesToWall : System.Windows.Forms.Form
	{
		public DlgCurvesToWall(ExternalCommandData cmdData)
		{
			this.m_Revit = cmdData;
			this.m_Initalized = false;
			this.InitializeComponent();
			this.InitializeGraphicsStyleList();
			this.InitControls();
			this.ReadData();
			this.m_Initalized = true;
		}

		public bool SendESC
		{
			get
			{
				return this.m_SendESC;
			}
			set
			{
				this.m_SendESC = value;
			}
		}

		public bool PickBotton
		{
			get
			{
				return this.m_PickBotton;
			}
		}

		public void InitControls()
		{
			Document document = this.m_Revit.Application.ActiveUIDocument.Document;
			this.m_basicWallTypes = new List<WallType>();
			this.m_curtainWallTypes = new List<WallType>();
			this.m_stackWallTypes = new List<WallType>();
			List<WallType> wallTypes = Common.GetWallTypes(document);
			foreach (Element element in wallTypes)
			{
				WallType wallType = element as WallType;
                if ((int)wallType.Kind == 0)
				{
					this.m_basicWallTypes.Add(wallType);
				}
                else if ((int)wallType.Kind == 2)
				{
					this.m_stackWallTypes.Add(wallType);
				}
                else if ((int)wallType.Kind == 1)
				{
					this.m_curtainWallTypes.Add(wallType);
				}
			}
			this.cmbWallLevel.Items.Add("未约束");
			Level currentViewLevel = AssistFunc.GetCurrentViewLevel(document);
			List<Level> sortLevels = Common.GetSortLevels(document, double.MinValue, double.MaxValue);
			foreach (Level level in sortLevels)
			{
				if (currentViewLevel != null)
				{
					if (currentViewLevel.Elevation < level.Elevation)
					{
						this.cmbWallLevel.Items.Add(level.Name);
					}
				}
				else
				{
					this.cmbWallLevel.Items.Add(level.Name);
				}
			}
			this.cmbWallFamily.SelectedIndex = 0;
			if (this.cmbWallLevel.Items.Count > 0)
			{
				this.cmbWallLevel.SelectedIndex = 0;
			}
			this.m_ExternalWallOffset = "0";
			this.tbOffset.Text = this.m_ExternalWallOffset;
			this.m_WallHeight = "8000";
			this.tbWallHeight.Text = this.m_WallHeight;
		}

		public void GetWallData(ref WallData data)
		{
			Document document = this.m_Revit.Application.ActiveUIDocument.Document;
			data.OutType = AssistFunc.GetWallTypeByName(document, this.cmbWallType.SelectedItem.ToString());
			data.OutOffset = AssistFunc.mmToFeet((double)((int)Convert.ToDouble(this.m_ExternalWallOffset)));
			if (this.tbWallHeight.Enabled)
			{
				data.OutWallHeight = AssistFunc.mmToFeet((double)((int)Convert.ToDouble(this.m_WallHeight)));
			}
			else
			{
				data.OutWallHeight = 0.0;
			}
			Level levelByName = AssistFunc.GetLevelByName(document, this.cmbWallLevel.SelectedItem.ToString());
			if (levelByName != null)
			{
				data.IdOutLevel = levelByName.Id;
				return;
			}
			data.IdOutLevel = ElementId.InvalidElementId;
		}

		public List<string> LayerStyleName()
		{
			List<string> list = new List<string>();
			for (int i = 0; i < this.checkedListBoxLayer.Items.Count; i++)
			{
				bool itemChecked = this.checkedListBoxLayer.GetItemChecked(i);
				if (itemChecked)
				{
					list.Add(this.m_LayerStyleNameList[i]);
				}
			}
			return list;
		}

		public void SetLayerStyle(string layerStyleName)
		{
			int num = this.m_LayerStyleNameList.FindIndex((string s) => s.CompareTo(layerStyleName) == 0);
			if (num != -1)
			{
				this.checkedListBoxLayer.SetItemChecked(num, true);
				this.m_SetLayerListCtrlScrollBar = true;
				this.checkedListBoxLayer.SelectedIndex = num;
			}
		}

		private void InitializeGraphicsStyleList()
		{
			Document document = this.m_Revit.Application.ActiveUIDocument.Document;
			FilteredElementCollector filteredElementCollector = new FilteredElementCollector(document).OfClass(typeof(GraphicsStyle));
			foreach (Element element in filteredElementCollector)
			{
				GraphicsStyle graphicsStyle = element as GraphicsStyle;
				if (graphicsStyle != null)
				{
					Category graphicsStyleCategory = graphicsStyle.GraphicsStyleCategory;
					if (graphicsStyleCategory != null)
					{
						Category parent = graphicsStyleCategory.Parent;
						if (parent != null && (parent.Name.CompareTo("线") == 0 || parent.Name.CompareTo("Lines") == 0) && graphicsStyleCategory.Name.CompareTo(graphicsStyle.Name) == 0 && this.checkedListBoxLayer.Items.IndexOf(graphicsStyleCategory.Name) == -1)
						{
							if (graphicsStyleCategory.Id.IntegerValue > 0)
							{
								this.checkedListBoxLayer.Items.Add(graphicsStyleCategory.Name);
								this.m_LayerStyleNameList.Add(graphicsStyleCategory.Name);
							}
							else
							{
								int integerValue = graphicsStyleCategory.Id.IntegerValue;
								if (integerValue == -2000078 || integerValue == -2000288 || integerValue == -2000285 || integerValue == -2000284 || integerValue == -2000287 || integerValue == -2000286 || integerValue == -2000043 || integerValue == -2000044 || integerValue == -2000042 || integerValue == -2009504)
								{
									this.checkedListBoxLayer.Items.Add(graphicsStyleCategory.Name);
									this.m_LayerStyleNameList.Add(graphicsStyleCategory.Name);
								}
							}
						}
					}
				}
			}
		}

		private void cmbOutFamily_SelectedIndexChanged(object sender, EventArgs e)
		{
			int selectedIndex = this.cmbWallFamily.SelectedIndex;
			this.ResetTypeCombobox(selectedIndex, true, this.cmbWallType);
		}

        private void ResetTypeCombobox(int index, bool isOutWall, System.Windows.Forms.ComboBox control)
		{
			control.Items.Clear();
			if (index == 0)
			{
				using (List<WallType>.Enumerator enumerator = this.m_basicWallTypes.GetEnumerator())
				{
					while (enumerator.MoveNext())
					{
						Element element = enumerator.Current;
						WallType walltype = element as WallType;
						this.InsertWallTypeToTypeCombobox(walltype, control);
					}
					goto IL_DA;
				}
			}
			if (1 == index)
			{
				using (List<WallType>.Enumerator enumerator2 = this.m_stackWallTypes.GetEnumerator())
				{
					while (enumerator2.MoveNext())
					{
						Element element2 = enumerator2.Current;
						WallType walltype2 = element2 as WallType;
						this.InsertWallTypeToTypeCombobox(walltype2, control);
					}
					goto IL_DA;
				}
			}
			if (2 == index)
			{
				foreach (Element element3 in this.m_curtainWallTypes)
				{
					WallType walltype3 = element3 as WallType;
					this.InsertWallTypeToTypeCombobox(walltype3, control);
				}
			}
			IL_DA:
			if (control.Items.Count > 0)
			{
				control.SelectedIndex = 0;
			}
		}

        private void InsertWallTypeToTypeCombobox(WallType walltype, System.Windows.Forms.ComboBox control)
		{
			control.Items.Add(walltype.Name);
		}

		private void SaveData()
		{
			string tempPath = Path.GetTempPath();
			string path = tempPath + "DlgCurvesToWallForm.dat";
			FileStream fileStream = new FileStream(path, FileMode.Create);
			StreamWriter streamWriter = new StreamWriter(fileStream);
			streamWriter.WriteLine(this.cmbWallFamily.SelectedItem.ToString());
			streamWriter.WriteLine(this.cmbWallType.SelectedItem.ToString());
			streamWriter.WriteLine(this.cmbWallLevel.SelectedItem.ToString());
			streamWriter.WriteLine(this.cbxBreak.Checked.ToString());
			streamWriter.WriteLine(base.Location.X);
			streamWriter.WriteLine(base.Location.Y);
			streamWriter.WriteLine(this.m_WallHeight);
			streamWriter.Flush();
			streamWriter.Close();
			fileStream.Close();
		}

		private bool ReadData()
		{
			string tempPath = Path.GetTempPath();
			string path = tempPath + "DlgCurvesToWallForm.dat";
			if (!File.Exists(path))
			{
				base.StartPosition = FormStartPosition.CenterScreen;
				return true;
			}
			base.StartPosition = FormStartPosition.Manual;
			FileStream fileStream = new FileStream(path, FileMode.Open);
			StreamReader streamReader = new StreamReader(fileStream);
			streamReader.BaseStream.Seek(0L, SeekOrigin.Begin);
			string text = streamReader.ReadLine();
			this.cmbWallFamily.SelectedItem = text;
			text = streamReader.ReadLine();
			this.cmbWallType.SelectedItem = text;
			text = streamReader.ReadLine();
			this.cmbWallLevel.SelectedItem = text;
			text = streamReader.ReadLine();
			text = streamReader.ReadLine();
			text = streamReader.ReadLine();
			text = streamReader.ReadLine();
			bool @checked = false;
			bool.TryParse(text, out @checked);
			this.cbxBreak.Checked = @checked;
			try
			{
				int x = Convert.ToInt32(streamReader.ReadLine());
				int y = Convert.ToInt32(streamReader.ReadLine());
                base.Location = new System.Drawing.Point(x, y);
				this.m_WallHeight = streamReader.ReadLine();
				if (this.m_WallHeight.CompareTo("") == 0)
				{
					this.m_WallHeight = "8000";
				}
				this.tbWallHeight.Text = this.m_WallHeight;
				this.ChangeWallHeightState();
			}
			catch (Exception)
			{
				this.m_WallHeight = "8000";
				this.tbWallHeight.Text = this.m_WallHeight;
				this.ChangeWallHeightState();
				streamReader.Close();
				fileStream.Close();
				return true;
			}
			streamReader.Close();
			fileStream.Close();
			return true;
		}

		private void ChangeWallHeightState()
		{
			if (this.cmbWallLevel.SelectedItem != null && this.cmbWallLevel.SelectedItem.ToString().CompareTo("未约束") == 0)
			{
				this.tbWallHeight.Enabled = true;
				return;
			}
			this.tbWallHeight.Enabled = false;
		}

		[DllImport("user32.dll", EntryPoint = "SendMessageA")]
		public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

		private void DlgAxisToWall_MouseLeave(object sender, EventArgs e)
		{
			if (!base.ClientRectangle.Contains(base.PointToClient(Cursor.Position)))
			{
				int wMsg = 7;
				DlgCurvesToWall.SendMessage(CmdWallCreateByCurves._hWndRevit.Handle, wMsg, IntPtr.Zero, IntPtr.Zero);
				return;
			}
			base.Focus();
		}

		[DllImport("user32.dll")]
		public static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);

		private void DlgAxisToWall_FormClosing(object sender, FormClosingEventArgs e)
		{
			this.SaveData();
			byte bVk = 27;
			int dwFlags = 0;
			int dwFlags2 = 2;
			DlgCurvesToWall.keybd_event(bVk, 0, dwFlags, 0);
			DlgCurvesToWall.keybd_event(bVk, 0, dwFlags2, 0);
		}

		private void cmbOutType_SelectedIndexChanged(object sender, EventArgs e)
		{
			Document document = this.m_Revit.Application.ActiveUIDocument.Document;
			WallType wallTypeByName = AssistFunc.GetWallTypeByName(document, this.cmbWallType.SelectedItem.ToString());
			double num = AssistFunc.feetToMM(wallTypeByName.Width);
			this.lbWallThickness.Text = "墙厚 " + num.ToString() + " mm";
			this.tbOffset.Text = "0";
		}

		private void btnNewOutWallType_Click(object sender, EventArgs e)
		{
			Document document = this.m_Revit.Application.ActiveUIDocument.Document;
			WallType wallTypeByName = AssistFunc.GetWallTypeByName(document, this.cmbWallType.SelectedItem.ToString());
			WallThicknessEditer wallThicknessEditer = new WallThicknessEditer(this.m_Revit);
			Transaction transaction = new Transaction(document);
			transaction.Start("new wall type");
			WallType wallType = null;
			string text = "";
			if (!wallThicknessEditer.NewWallType(wallTypeByName, ref wallType, ref text))
			{
				transaction.RollBack();
				return;
			}
			transaction.Commit();
			int selectedIndex = this.cmbWallFamily.SelectedIndex;
			if (selectedIndex == 0)
			{
				this.m_basicWallTypes.Add(wallType);
			}
			else if (1 == selectedIndex)
			{
				this.m_stackWallTypes.Add(wallType);
			}
			else if (2 == selectedIndex)
			{
				this.m_curtainWallTypes.Add(wallType);
			}
			this.cmbWallType.Items.Add(wallType.Name);
			this.cmbWallType.Text = wallType.Name;
		}

		private void tbOffset_TextChanged(object sender, EventArgs e)
		{
			Document document = this.m_Revit.Application.ActiveUIDocument.Document;
			WallType wallTypeByName = AssistFunc.GetWallTypeByName(document, this.cmbWallType.SelectedItem.ToString());
			double num = AssistFunc.feetToMM(wallTypeByName.Width);
			try
			{
				if (this.tbOffset.Text.CompareTo("-") == 0)
				{
					return;
				}
				double value = (double)int.Parse(this.tbOffset.Text);
				if (!Geometry.Lessthan_Or_Equal(Math.Abs(value), num / 2.0))
				{
					MessageBox.Show("偏移范围不能超出半个墙厚.", "盈建科提示");
					this.tbOffset.Text = this.m_ExternalWallOffset;
					return;
				}
			}
			catch (FormatException)
			{
				MessageBox.Show("请输入一个整数.", "盈建科提示");
				this.tbOffset.Text = this.m_ExternalWallOffset;
			}
			this.m_ExternalWallOffset = this.tbOffset.Text;
		}

		private void btnSelectLayer_Click(object sender, EventArgs e)
		{
			this.m_SendESC = true;
			this.m_PickBotton = true;
			int wMsg = 7;
			DlgCurvesToWall.SendMessage(CmdWallCreateByCurves._hWndRevit.Handle, wMsg, IntPtr.Zero, IntPtr.Zero);
			byte bVk = 27;
			int dwFlags = 0;
			int dwFlags2 = 2;
			DlgCurvesToWall.keybd_event(bVk, 0, dwFlags, 0);
			DlgCurvesToWall.keybd_event(bVk, 0, dwFlags2, 0);
		}

		private void checkedListBoxLayer_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (!this.m_Initalized)
			{
				return;
			}
			if (this.m_SetLayerListCtrlScrollBar)
			{
				this.m_SetLayerListCtrlScrollBar = false;
				return;
			}
			this.m_SendESC = true;
			this.m_PickBotton = false;
			int wMsg = 7;
			DlgCurvesToWall.SendMessage(CmdWallCreateByCurves._hWndRevit.Handle, wMsg, IntPtr.Zero, IntPtr.Zero);
			byte bVk = 27;
			int dwFlags = 0;
			int dwFlags2 = 2;
			DlgCurvesToWall.keybd_event(bVk, 0, dwFlags, 0);
			DlgCurvesToWall.keybd_event(bVk, 0, dwFlags2, 0);
		}

		private void checkedListBoxLayer_MouseClick(object sender, MouseEventArgs e)
		{
			if (this.checkedListBoxLayer.SelectedItem != null)
			{
				int num = ((ListBox)sender).IndexFromPoint(e.X, e.Y);
				if (num == -1)
				{
					this.checkedListBoxLayer.ClearSelected();
				}
			}
		}

		private void checkedListBoxLayer_MouseDoubleClick(object sender, MouseEventArgs e)
		{
			if (this.checkedListBoxLayer.SelectedItem != null)
			{
				int num = ((ListBox)sender).IndexFromPoint(e.X, e.Y);
				if (num == -1)
				{
					this.checkedListBoxLayer.ClearSelected();
				}
			}
		}

		private void DlgCurvesToWall_Load(object sender, EventArgs e)
		{
		}

		private void tbOutWallHeight_TextChanged(object sender, EventArgs e)
		{
			try
			{
				double val = (double)int.Parse(this.tbWallHeight.Text);
				if (Geometry.Lessthan_Or_Equal(val, 0.0))
				{
					MessageBox.Show("请输入一个大于零的正整数.", "盈建科提示");
					this.tbWallHeight.Text = this.m_WallHeight;
					return;
				}
			}
			catch (FormatException)
			{
				MessageBox.Show("请输入一个大于零的正整数.", "盈建科提示");
				this.tbWallHeight.Text = this.m_WallHeight;
			}
			this.m_WallHeight = this.tbWallHeight.Text;
		}

		private void cmbOutLevel_SelectedIndexChanged(object sender, EventArgs e)
		{
			this.ChangeWallHeightState();
		}

		public ExternalCommandData m_Revit;

		private List<string> m_LayerStyleNameList = new List<string>();

		private List<WallType> m_basicWallTypes;

		private List<WallType> m_stackWallTypes;

		private List<WallType> m_curtainWallTypes;

		private string m_ExternalWallOffset = "0";

		private string m_WallHeight = "8000";

		private bool m_Initalized;

		private bool m_SendESC;

		private bool m_PickBotton;

		private bool m_SetLayerListCtrlScrollBar;
	}
}
